package ltd.hyangyang.rpc.core.registory.zook;

import ltd.hyangyang.rpc.common.bean.RpcConfig;
import ltd.hyangyang.rpc.common.bean.RpcProperties;
import ltd.hyangyang.rpc.common.exception.ExceptionEnum;
import ltd.hyangyang.rpc.common.exception.RpcException;
import ltd.hyangyang.rpc.common.utils.PropertiesReadUtils;
import ltd.hyangyang.rpc.core.registory.DiscoverService;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;


public class ZookDisCoverService implements DiscoverService {

    Logger logger = Logger.getGlobal();
    RpcProperties rpcProperties;

    //存储服务端地址
    ConcurrentHashMap<String,List<String>> serverInterface = new ConcurrentHashMap();
    //依赖
    public ZookDisCoverService() throws IOException {
        rpcProperties = PropertiesReadUtils.initProperties();
    }

    //TODO 监听服务端的变化
    //服务注册
    @Override
    public List<String> discover(RpcConfig rpcConfig) throws Exception {
        List<String> nodeList = serverInterface.get(rpcConfig.getServiceName());
        if (!StringUtils.isEmpty(nodeList)){
            return nodeList;
        }
        String serviceName = rpcConfig.getServiceName();
        if (StringUtils.isEmpty(serviceName)){
            //抛出异常
            throw new RpcException(ExceptionEnum.INPUT_NOT_EMPTY.getMsg());
        }

        CuratorFramework client = CuratorUtils.init(rpcProperties.getAddr());

        nodeList = CuratorUtils.getService(client,rpcConfig);
        serverInterface.put(rpcConfig.getServiceName(),nodeList);

        logger.info(nodeList.toString());
        return nodeList;
    }
}
